package com.inxedu.os.edu.controller.Student;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.inxedu.os.common.PageEntity;
import com.inxedu.os.common.util.user.UserStudentUtil;
import com.inxedu.os.edu.pojo.EduUser;
import com.inxedu.os.edu.pojo.EduUserLoginLog;
import com.inxedu.os.edu.pojo.QueryUser;
import com.inxedu.os.edu.service.student.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学员管理Controller
 */
@Controller
@RequestMapping("/admin/user")
@Api(value = "后台学员管理接口",tags = "后台学员管理接口")
public class studentController {

    @Autowired
    private StudentService studentService;

    /**
     * 获取学员列表
     * @param record
     * @return
     */
    @RequestMapping(value = "/getuserList",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "获取学员列表",notes = "获取学员列表")
    @ApiImplicitParams({ @ApiImplicitParam(name = "record",value = "模糊查询学员列表条件类",paramType = "query")
            ,@ApiImplicitParam(name = "page",value = "获取分页",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "isAvalible",value = "查询条件状态",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "keyWord",value = "查询条件昵称等",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "beginCreateTime",value = "开始注册时间",dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "endCreateTime",value = "结束注册时间",dataType = "Date",paramType = "query")})

    public ModelAndView  toStudentList(@Param("record") QueryUser record, @RequestParam(defaultValue = "1") int page){

        ModelAndView model = new ModelAndView();
        model.setViewName("view/inxedu/admin/user/user-list");
        //设置分页
        PageHelper.startPage(page,10);
        List<EduUser> userList = studentService.findByUserMh(record);

        PageInfo<EduUser> info = new PageInfo<EduUser>(userList);
        model.addObject("page",info);
        model.addObject("userList",userList);
        return model;
    }

    /**
     * 批量开通学员
     * @return
     */
    @RequestMapping(value = "/toBatchOpen",method = RequestMethod.GET)
    @ApiOperation(value ="跳转批量开通学员页面",notes = "批量开通学员页面")
    public String toAddStudent(){

        return "/view/inxedu/admin/user/batchOpen";
    }



    /**
     * 学员密码修改工具类
     * @param success
     * @param message
     * @param entity
     * @return
     */
    public Map<String, Object> setJson(boolean success, String message, Object entity) {
        Map<String, Object> json = new HashMap();
        json.put("success", success);
        json.put("message", message);
        json.put("entity", entity);
        return json;
    }

    /**
     * 修改学员密码
     * @param request
     * @param userId
     * @return
     */
    @RequestMapping(value = "/updateUserPwd",method = {RequestMethod.GET,RequestMethod.POST})       //admin/user/updateUserPwd
    @ResponseBody
    @ApiOperation(value = "修改学员密码",notes = "修改学员密码")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "学员id",dataType = "int",paramType = "query"),
    @ApiImplicitParam(name = "password",value = "获取输入密码",dataType = "String",paramType = "query")})

    public Map<String,Object> toUpdateUserPwd(HttpServletRequest request,@ModelAttribute("user.userId") int userId,@ModelAttribute("user.password") String password) {
        Map<String,Object> json = new HashMap<String,Object>();

        EduUser eduUser = new EduUser();
        eduUser.setUserId(userId);
        eduUser.setPassword(password);

        if(password==null || password.trim().length()==0 || !UserStudentUtil.isPasswordAvailable(password)){
            json = this.setJson(false, "密码由字母和数字组成且≥6位≤16位", null);
            return json;
        }
        String passwords = request.getParameter("passwords")==null?"":request.getParameter("passwords");
        if(!password.equals(passwords)){
            json = this.setJson(false, "两次密码不一至！", null);
            return json;
        }
        studentService.updateUserPwd(eduUser);
        json = this.setJson(true, "修改成功", null);
        return json;
    }

    /**
     * 修改学员账号状态
     * @param userId
     * @return
     */
    @RequestMapping(value = "/updateuserstate",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "修改学员账号状态",notes = "修改学员账号状态")
    @ApiImplicitParam(name = "userId",value = "学员id",dataType = "int",paramType = "query")
    public Map<String,Object> updateState(@ModelAttribute("user.userId") int userId){
        Map<String,Object> json = new HashMap<String,Object>();
        int isAvalible = studentService.findByUserId(userId);

        //1正常   2冻结
        if (isAvalible==1){
            EduUser eduUser = new EduUser();
            eduUser.setIsAvalible((byte) 2);
            eduUser.setUserId(userId);
            studentService.updateByUserState(eduUser);
            json = this.setJson(true, null, null);
        }
        if (isAvalible==2){
            EduUser eduUser = new EduUser();
            eduUser.setIsAvalible((byte) 1);
            eduUser.setUserId(userId);
            studentService.updateByUserState(eduUser);
            json = this.setJson(true, null, null);
        }
        return json;
    }

    /**
     * 查看用户登陆日志
     * @param request
     * @param userId
     * @param
     * @return
     */
    @RequestMapping(value = "/lookuserlog/{userId}",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查看用户登陆日志",notes = "查看用户登陆日志")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "用户Id",dataType = "int",paramType = "path"),
            @ApiImplicitParam(name = "page",value = "分页信息",dataType = "int",paramType = "query")
    })
    public ModelAndView lookUserLog(HttpServletRequest request, @PathVariable("userId") int userId,@RequestParam(defaultValue = "1") int page){
        ModelAndView model = new ModelAndView();
        model.setViewName("view/inxedu/admin/user/user-loginlog");
        PageHelper.startPage(page,10);
        List<EduUserLoginLog> logList = studentService.findUserLogPage(userId);
        PageInfo<EduUserLoginLog> info = new PageInfo<EduUserLoginLog>(logList);
//        System.out.println(logList);
        model.addObject("page",info);
        model.addObject("logList",logList);
        model.addObject("userId",userId);
        return model;
    }

    /**
     * 学员信息excel格式拼接
     * @return
     */
    public List<List<String>> userJoint(List<EduUser> userList){
        List<List<String>> list = new ArrayList<List<String>>();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < userList.size(); i++) {
            List<String> small = new ArrayList<String>();
            small.add(userList.get(i).getUserId() + "");
            small.add(userList.get(i).getEmail());
            small.add(userList.get(i).getMobile());
            small.add(userList.get(i).getUserName());
            small.add(userList.get(i).getShowName());
            if (userList.get(i).getSex() == 0||userList.get(i).getSex() == null||userList.get(i).getSex().equals("")) {
                small.add("--");
            } else if (userList.get(i).getSex() == 1) {
                small.add("男");
            } else {
                small.add("女");
            }
            small.add(String.valueOf(userList.get(i).getAge()));
            small.add(format.format(userList.get(i).getCreateTime()));
            if(userList.get(i).getIsAvalible()==null || userList.get(i).getIsAvalible().equals("")){
                small.add("未知");
            }else if (userList.get(i).getIsAvalible() == 1) {
                small.add("正常");
            } else if (userList.get(i).getIsAvalible() == 2) {
                small.add("冻结");
            }
            list.add(small);
        }
        return list;
    }

    /**
     * 学员导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "学员导出Excel",notes = "导出Excel")
    @ApiImplicitParams({ @ApiImplicitParam(name = "record",value = "模糊查询学员列表条件类",paramType = "query"),
            @ApiImplicitParam(name = "isAvalible",value = "查询条件状态",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "keyWord",value = "查询条件昵称等",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "beginCreateTime",value = "开始注册时间",dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "endCreateTime",value = "结束注册时间",dataType = "Date",paramType = "query")})
    public ModelAndView userListExport(HttpServletRequest request, HttpServletResponse response,@Param("record") QueryUser record){
        ModelAndView modelAndView = new ModelAndView();
        try {
           modelAndView.setViewName("redirect:/admin/user/getuserList");
            //指定文件生成路径
            String dir = request.getSession().getServletContext().getRealPath("/excelfile/user");
//            //指定文件的保存类型。
//            response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            response.setCharacterEncoding("utf-8");

            //文件名
            String expName = "学员信息" + Math.random() * 10;
//            URLEncoder.encode(expName,"UTF-8");
            //表头信息
            String[] headName = {"ID", "邮箱", "手机", "用户名", "昵称", "性别", "年龄", "注册时间", "状态"};

            List<EduUser> userList = studentService.findByUserMh(record);
            modelAndView.addObject("userList",userList);
            List<File> srcfile = new ArrayList<>();

            List<List<String>> list = userJoint(userList);
//            response.setCharacterEncoding("utf-8");
            File file = UserStudentUtil.createExcel(headName, list, expName, dir);
            srcfile.add(file);
        }catch (Exception e){
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 批量开通学员提交
     * @param myfile
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/importExcel",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "批量开通学员提交",notes = "提交批量开通学员")
    @ApiImplicitParam(name = "myFile",value = "Excel文件",dataType = "file",paramType = "query")
    public ModelAndView importExcel(HttpServletRequest request,@RequestParam("myFile") MultipartFile myfile) {//,@RequestParam("mark") Integer mark
        ModelAndView model = new ModelAndView();
        try {
            String s = studentService.AddImportExcel(request, myfile);//, mark
            System.out.println(s);
            request.setAttribute("msg", s);
            if(s==null||s.equals("")){
                model.setViewName("view/common/success");
            }else {
                model.setViewName("view/common/msg_error");
            }
        }catch (Exception e){
            e.printStackTrace();
        }


//        ExcelUtil excelUtil = new ExcelUtil();

        return model;
    }

}

